package com.ChainBizPro.system.controller;

import com.ChainBizPro.system.annotation.AuthCheck;
import com.ChainBizPro.system.common.BaseResponse;
import com.ChainBizPro.system.common.DeleteRequest;
import com.ChainBizPro.system.common.ErrorCode;
import com.ChainBizPro.system.common.ResultUtils;
import com.ChainBizPro.system.constant.UserConstant;
import com.ChainBizPro.system.exception.BusinessException;
import com.ChainBizPro.system.exception.ThrowUtils;
import com.ChainBizPro.system.model.domain.Suppliers;
import com.ChainBizPro.system.model.domain.User;
import com.ChainBizPro.system.model.dto.Suppliers.SupplierUpdateMyRequest;
import com.ChainBizPro.system.model.dto.Suppliers.SuppliersAddRequest;
import com.ChainBizPro.system.model.dto.Suppliers.SuppliersQueryRequest;
import com.ChainBizPro.system.model.dto.Suppliers.SuppliersUpdateRequest;
import com.ChainBizPro.system.model.vo.LoginUserVO;
import com.ChainBizPro.system.model.vo.SuppliersVO;
import com.ChainBizPro.system.service.SuppliersService;
import com.ChainBizPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 供应商接口
 *
 * @author liusijia
 */
@RestController
@RequestMapping("/suppliers")
@Api(tags = "供应商接口")
@Slf4j
public class SuppliersController {

    @Resource
    private UserService userService;

    @Resource
    private SuppliersService suppliersService;

    // region 增删改查

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 创建供应商
     *
     * @param suppliersAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建供应商")
    public BaseResponse<Long> addSupplier(@RequestBody SuppliersAddRequest suppliersAddRequest) {
        if (suppliersAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        if (suppliersAddRequest.getSupplierName() == null || suppliersAddRequest.getSupplierName().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "供应商名称不能为空");
        }
        if (suppliersAddRequest.getContactPersonName() == null || suppliersAddRequest.getContactPersonName().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "负责人姓名不能为空");
        }
        if (suppliersAddRequest.getContactPhone() == null || suppliersAddRequest.getContactPhone().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "联系电话不能为空");
        }
        if (suppliersAddRequest.getContactPhone().length() != 11) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "联系电话长度不正确");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", suppliersAddRequest.getContactPersonName());
        User user = userService.getOne(queryWrapper);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "该用户不存在");
        // 添加用户角色为负责人
        user.setUserRole(UserConstant.CONTACT_ROLE);
        Suppliers supplier = new Suppliers();
        supplier.setContactPersonId(user.getId());
        BeanUtils.copyProperties(suppliersAddRequest, supplier);
        userService.updateById(user);
        boolean result = suppliersService.save(supplier);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建失败");
        return ResultUtils.success(supplier.getSupplierId());
    }

    /**
     * 删除供应商
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除供应商")
    public BaseResponse<Boolean> deleteSupplier(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = suppliersService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新供应商 (仅管理员)
     *
     * @param suppliersUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新供应商 (仅管理员)")
    public BaseResponse<Boolean> updateSupplierByAdmin(@RequestBody SuppliersUpdateRequest suppliersUpdateRequest) {
        if (suppliersUpdateRequest.getSupplierId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Suppliers supplier = new Suppliers();

        QueryWrapper<Suppliers> queryWrapperSuppliers = new QueryWrapper<>();
        QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();

        queryWrapperSuppliers.eq("supplierId", suppliersUpdateRequest.getSupplierId());
        Suppliers supplierOld = suppliersService.getOne(queryWrapperSuppliers);

        if (suppliersUpdateRequest.getSupplierName() == null || suppliersUpdateRequest.getSupplierName().equals("")) {
            suppliersUpdateRequest.setSupplierName(supplierOld.getSupplierName());
        }
        if (suppliersUpdateRequest.getAddress() == null || suppliersUpdateRequest.getAddress().equals("")) {
            suppliersUpdateRequest.setAddress(supplierOld.getAddress());
        }
        if (suppliersUpdateRequest.getContactPersonName() == null || suppliersUpdateRequest.getContactPersonName().equals("")) {
            QueryWrapper<User> id = queryWrapperUser.eq("id", supplierOld.getContactPersonId());
            ThrowUtils.throwIf(userService.getOne(id) == null, ErrorCode.NOT_FOUND_ERROR, "请添加负责任人");
            suppliersUpdateRequest.setContactPersonName(userService.getOne(id).getUserName());
        }
        if (suppliersUpdateRequest.getContactPhone() == null || suppliersUpdateRequest.getContactPhone().equals("")) {
            suppliersUpdateRequest.setContactPhone(supplierOld.getContactPhone());
        }

        // 插入负责人id
        if (suppliersUpdateRequest.getContactPersonName() != null) {
            queryWrapperUser.eq("userName", suppliersUpdateRequest.getContactPersonName());
            ThrowUtils.throwIf(userService.getOne(queryWrapperUser) == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
            supplier.setContactPersonId(userService.getOne(queryWrapperUser).getId());
        }

        BeanUtils.copyProperties(suppliersUpdateRequest, supplier);
        boolean result = suppliersService.updateById(supplier);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取供应商（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "根据 id 获取供应商（仅管理员）")
    public BaseResponse<Suppliers> getSuppliersById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Suppliers supplier = suppliersService.getById(id);
        ThrowUtils.throwIf(supplier == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(supplier);
    }

    /**
     * 分页获取供应商列表（管理员和用户）
     *
     * @param suppliersQueryRequest
     * @return
     */
    @PostMapping("/get/all/admin")
    @ApiOperation(value = "分页获取全部供应商列表（管理员和用户）")
    public BaseResponse<Page<SuppliersVO>> listSuppliersByPage(@RequestBody SuppliersQueryRequest suppliersQueryRequest) {
        long current = suppliersQueryRequest.getCurrent() == 0 ? 1 : suppliersQueryRequest.getCurrent();
        long size = suppliersQueryRequest.getPageSize() == 0 ? 10 : suppliersQueryRequest.getPageSize();

        //分页信息封装Page对象
        Page<SuppliersVO> pageParam = new Page(current, size);
        Page<SuppliersVO> queryWrapper = suppliersService.getQueryWrapper(pageParam, suppliersQueryRequest);
        return ResultUtils.success(queryWrapper);
    }

    /**
     * 负责人分页获取负责的全部供应商列表
     *
     * @param suppliersQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/all/contact")
    @ApiOperation(value = "负责人分页获取负责的全部供应商列表")
    public BaseResponse<Page<SuppliersVO>> listSuppliersVOByPage(@RequestBody SuppliersQueryRequest suppliersQueryRequest, HttpServletRequest request) {
        if (suppliersQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        long current = suppliersQueryRequest.getCurrent() == 0 ? 1 : suppliersQueryRequest.getCurrent();
        long size = suppliersQueryRequest.getPageSize() == 0 ? 10 : suppliersQueryRequest.getPageSize();
        Page<SuppliersVO> pageParam = new Page<>(current, size);
        Long userId = userService.getLoginUser(request).getId();

        Page<SuppliersVO> supplierPage = suppliersService.getQueryWrapperByMy(pageParam, suppliersQueryRequest, userId);

        return ResultUtils.success(supplierPage);
    }

    // endregion

    /**
     * 负责人更新供应商信息
     *
     * @param supplierUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    @ApiOperation(value = "负责人更新供应商信息")
    public BaseResponse<Boolean> updateSupplier(@RequestBody SupplierUpdateMyRequest supplierUpdateMyRequest, HttpServletRequest request) {
        if (supplierUpdateMyRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.CONTACT_ROLE)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        QueryWrapper<Suppliers> suppliersQuery = new QueryWrapper<>();
        suppliersQuery.eq("supplierId", supplierUpdateMyRequest.getSupplierId());
        Suppliers suppliers = suppliersService.getOne(suppliersQuery);
        ThrowUtils.throwIf(suppliers == null, ErrorCode.NOT_FOUND_ERROR, "供应商不存在");
        if (supplierUpdateMyRequest.getSupplierName() == null || supplierUpdateMyRequest.getSupplierName().equals("")) {
            supplierUpdateMyRequest.setSupplierName(suppliers.getSupplierName());
        }
        if (supplierUpdateMyRequest.getAddress() == null || supplierUpdateMyRequest.getAddress().equals("")) {
            supplierUpdateMyRequest.setAddress(suppliers.getAddress());
        }
        if (supplierUpdateMyRequest.getContactPhone() == null || supplierUpdateMyRequest.getContactPhone().equals("")) {
            supplierUpdateMyRequest.setContactPhone(suppliers.getContactPhone());
        }
        BeanUtils.copyProperties(supplierUpdateMyRequest, suppliers);
        boolean result = suppliersService.updateById(suppliers);
        return ResultUtils.success(result);
    }
}
